package com.controller;

import com.alibaba.fastjson2.JSONObject;
import com.config.Msg;
import com.dao.db1.LoginDao;
import com.dao.db2.KhJwDao;
import com.dao.db2.YwyJwDao;
import com.pojo.K3bm;
import com.pojo.Kh;
import com.pojo.User;
import com.server.GetKhServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@CrossOrigin
@RestController
public class KhJwController {
    private final KhJwDao khJwDao;
    private final GetKhServer getKhServer;
    private final LoginDao loginDao;
    private final YwyJwDao ywyJwDao;
    @Autowired
    public KhJwController(KhJwDao khJwDao, GetKhServer getKhServer,YwyJwDao ywyJwDao,LoginDao loginDao)  {
        this.khJwDao = khJwDao;
        this.getKhServer = getKhServer;
        this.ywyJwDao = ywyJwDao;
        this.loginDao = loginDao;
    }

    @RequestMapping("/update/Jw/Kh")
    @ResponseBody
    public Msg updateJwKh(@RequestBody JSONObject jsonObject) {
        Msg msg = new Msg();
        //
        List<Kh> list = khJwDao.selectKh();
        List<Kh> list1 = getKhServer.selectKh();
        List<Kh> khNotInList1 = list.stream()
                .filter(kh -> list1.stream().noneMatch(kh1 -> Objects.equals(kh.getKhbm(), kh1.getKhbm())))
                .collect(Collectors.toList());

        for (Kh kh : khNotInList1) {
            int i = getKhServer.addKh(kh.getId(), kh.getKhbm(), kh.getKhmc());
            if (i==0){
                msg.setCode(500);
                msg.setMessage("更新失败");
                return msg;
            }
        }
        msg.setCode(200);
        msg.setMessage("更新成功");

        return msg;
    }
    @RequestMapping("/insert/Jw/Ywy")
    @ResponseBody
    public Msg insertJwKha(@RequestBody JSONObject jsonObject) {
        Msg msg = new Msg();
        List<User> user = ywyJwDao.selectJwYwy();
        List<User> user1= loginDao.getUser();
        List<User> khNotInList1 = user.stream()
                .filter(kh -> user1.stream().noneMatch(kh1 -> Objects.equals(kh.getUsername(), kh1.getUsername())))
                .collect(Collectors.toList());
        for (User user3 : khNotInList1) {
            int i = loginDao.addYwy(user3.getUsername(), "0", 0,user3.getName(),user3.getDepartmentId(),user3.getSszz(),user3.getSszz());
            if (i==0){
                msg.setCode(500);
                msg.setMessage("更新失败");
                return msg;
            }
        }
        msg.setCode(200);
        msg.setMessage("更新完成");
        return msg;
    }
}
